<template>
  <xyEnergyhead>
    <EnergyHead
      title="分组能耗统计"
      icon="tree"
      :info="info"
      @download-chart="downloadChart"
      @init-chart="initChart"
    ></EnergyHead>
    <div v-if="typeShow" class="chart-container">
      <div ref="groupChartEnergy" class="chart-wrapper"></div>
      <div ref="groupChartBill" class="chart-wrapper"></div>
    </div>
    <div v-if="!typeShow" class="table-view">
      <el-table
        :data="tableData"
        style="width: 100%"
        size="large"
        :header-cell-style="{ background: '#0066ff0d', color: '#0066ff' }"
      >
        <el-table-column prop="date" label="区域">
          <template slot-scope="scope">
            <span
              ><i
                v-if="scope.row.date === '办公区域'"
                class="el-icon-office-building"
                style="color: #0066ff; font-weight: bold; padding-right: 5px"
              ></i>
              <i
                v-if="scope.row.date === '生产区域'"
                class="el-icon-s-shop"
                style="color: #7b2cbf; font-weight: bold; padding-right: 5px"
              ></i>
              <i
                v-if="scope.row.date === '生活区域'"
                class="el-icon-s-home"
                style="color: #ff3366; font-weight: bold; padding-right: 5px"
              ></i>
              <i
                v-if="scope.row.date === '其他区域'"
                class="el-icon-more"
                style="color: #ffaa00; font-weight: bold; padding-right: 5px"
              ></i
              >{{ scope.row.date }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="name" label="电量(kWh)"> </el-table-column>
        <el-table-column prop="bill" label="电费(元)"> </el-table-column>
        <el-table-column prop="change" label="占比变化"> </el-table-column>
        <el-table-column prop="address" label="趋势">
          <template slot-scope="scope">
            <span :class="scope.row.address === '4.5%' ? 'trend-up' : 'trend-down'"
              ><i
                :class="scope.row.address === '4.5%' ? 'el-icon-top' : 'el-icon-bottom'"
              ></i
              >{{ scope.row.address }}</span
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 详细统计信息 -->
    <el-card class="main-analysis">
      <div class="main-analysis-header">
        <svg-icon icon-class="dataCenter"></svg-icon>
        <span class="main-analysis-title">分组能耗详细分析</span>
      </div>
      <div class="main-analysis-content">
        <div class="main-analysis-content-item">
          <div>办公区域最大能耗</div>
          <div class="main-analysis-content-item-value">680 kWh (11:30)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>生产区域最大能耗</div>
          <div class="main-analysis-content-item-value">490 kWh (14:00)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>生活区域最大能耗</div>
          <div class="main-analysis-content-item-value">275 kWh (20:00)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>峰值时段总能耗</div>
          <div class="main-analysis-content-item-value">850 kWh</div>
        </div>
        <div class="main-analysis-content-item">
          <div>低谷时段总能耗</div>
          <div class="main-analysis-content-item-value">320 kWh</div>
        </div>
        <div class="main-analysis-content-item">
          <div>平段时段总能耗</div>
          <div class="main-analysis-content-item-value">480 kWh</div>
        </div>
      </div>
    </el-card>
  </xyEnergyhead>
</template>

<script>
import xyEnergyhead from "../../components/xy-energy-head.vue";
import EnergyHead from "./EnergyHead.vue";
import * as echarts from "echarts";

export default {
  components: { xyEnergyhead, EnergyHead },
  props: {
    typeShow: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      groupChartEnergy: null,
      groupChartBill: null, // 添加第二个图表引用
      currentPage: 1, // 添加 currentPage 数据属性
      pageSize: 10, // 添加 pageSize 数据属性
      total: 0, // 添加 total 数据属性
      currentTimeDimension: "day", // 默认显示日维度数据
      chartData: {
        day: {
          labels: ["办公区域", "生产区域", "生活区域", "其他区域"],
          energyData: [520, 380, 220, 130],
          billData: [416, 247, 110, 65],
          colors: ["#0066ff", "#7b2cbf", "#ff3366", "#ffaa00"],
        },
        month: {
          labels: ["办公区域", "生产区域", "生活区域", "其他区域"],
          energyData: [15600, 11400, 6600, 3900],
          billData: [12480, 7410, 3300, 1950],
          colors: ["#0066ff", "#7b2cbf", "#ff3366", "#ffaa00"],
        },
        year: {
          labels: ["办公区域", "生产区域", "生活区域", "其他区域"],
          energyData: [187200, 136800, 79200, 46800],
          billData: [149760, 88920, 39600, 23400],
          colors: ["#0066ff", "#7b2cbf", "#ff3366", "#ffaa00"],
        },
      },
      tableData: [
        {
          date: "办公区域",
          name: "520",
          bill: "65.2元",
          change: "0.5%",
          address: "4.5%",
        },
        {
          date: "生产区域",
          name: "520",
          bill: "65.2元",
          change: "0.5%",
          address: "4.5%",
        },
        {
          date: "生活区域",
          name: "520",
          bill: "65.2元",
          change: "0.5%",
          address: "4.5%",
        },
        {
          date: "其他区域",
          name: "520",
          bill: "65.2元",
          change: "0.5%",
          address: "4.5%",
        },
      ],
      info: {
        title: "分组能耗统计详情",
        listInfo: [
          {
            title: "此图表展示了不同区域或设备分组的能耗统计信息。",
          },
          {
            title: "通过分组统计，可以识别能耗热点区域，有针对性地制定节能措施。",
          },
          {
            title: "表格数据展示了各分组的详细能耗情况和变化趋势。",
          },
        ],
      },
    };
  },
  mounted() {
    if (this.typeShow) {
      this.$nextTick(() => {
        this.initGroupChart();
      });
    }
    this.updateTableData();
  },
  beforeDestroy() {
    if (this.groupChartEnergy) {
      this.groupChartEnergy.dispose();
    }
    if (this.groupChartBill) {
      this.groupChartBill.dispose();
    }
  },
  watch: {
    typeShow: {
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            this.initGroupChart();
          });
        } else {
          if (this.groupChartEnergy) {
            this.groupChartEnergy.dispose();
            this.groupChartEnergy = null;
          }
          if (this.groupChartBill) {
            this.groupChartBill.dispose();
            this.groupChartBill = null;
          }
          this.updateTableData();
        }
      },
      immediate: true,
    },
    currentTimeDimension: {
      handler() {
        if (this.typeShow) {
          this.$nextTick(() => {
            this.initGroupChart();
          });
        } else {
          this.updateTableData();
        }
      },
    },
  },
  methods: {
    initChart() {
      if (this.typeShow) {
        this.initGroupChart();
      } else {
        this.updateTableData();
      }
    },
    switchTimeDimension(dimension) {
      this.currentTimeDimension = dimension;
    },

    updateTableData() {
      // 表格数据更新逻辑
    },

    // 添加分页处理方法
    handlerPagination(page) {
      console.log(page, "分页信息");
      // 正确更新 currentPage 和 pageSize
      this.currentPage = page.pageNum;
      this.pageSize = page.pageSize;
      // 调用数据初始化方法
      this.initTableData();
    },

    // 添加初始化表格数据方法
    initTableData() {
      // 这里应该调用实际的API获取数据
      // 示例代码：
      // const params = {
      //   pageNum: this.currentPage,
      //   pageSize: this.pageSize
      // };
      // 调用API获取数据
      // apiCall(params).then(response => {
      //   this.tableData = response.data;
      //   this.total = response.total;
      // });

      // 模拟数据更新
      console.log(`获取第${this.currentPage}页数据，每页${this.pageSize}条`);
    },

    initGroupChart() {
      if (!this.$refs.groupChartEnergy || !this.$refs.groupChartBill) return;

      // 初始化电量图表
      if (this.groupChartEnergy) {
        this.groupChartEnergy.dispose();
      }
      this.groupChartEnergy = echarts.init(this.$refs.groupChartEnergy);

      // 初始化电费图表
      if (this.groupChartBill) {
        this.groupChartBill.dispose();
      }
      this.groupChartBill = echarts.init(this.$refs.groupChartBill);

      const currentData = this.chartData[this.currentTimeDimension];
      const energyTotal = currentData.energyData.reduce((sum, value) => sum + value, 0);
      const billTotal = currentData.billData.reduce((sum, value) => sum + value, 0);

      // 电量图表配置
      const energyOption = {
        title: {
          text: this.getTimeDimensionTitle() + " - 电量",
          left: "center",
          textStyle: {
            color: "#64748b",
            fontSize: 14,
            fontWeight: "bold",
          },
          top: 20,
        },
        tooltip: {
          trigger: "item",
          formatter: (params) => {
            const percentage = ((params.value / energyTotal) * 100).toFixed(1);
            return `${params.name}<br/>${params.marker} ${params.value} kWh (${percentage}%)`;
          },
        },
        legend: {
          show: true,
          bottom: 0,
          left: "center",
          textStyle: {
            color: "#64748b",
          },
        },
        series: [
          {
            name: "分组能耗",
            type: "pie",
            radius: ["40%", "70%"],
            center: ["50%", "55%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 5,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: {
              show: true,
              formatter: (params) => {
                const percentage = ((params.value / energyTotal) * 100).toFixed(1);
                return `{name|${params.name}}\n{value|${params.value} kWh}\n{percentage|${percentage}%}`;
              },
              rich: {
                name: {
                  fontSize: 10,
                  color: "#64748b",
                },
                value: {
                  fontSize: 12,
                  fontWeight: "bold",
                  color: "#333",
                  lineHeight: 18,
                },
                percentage: {
                  fontSize: 10,
                  color: "#999",
                },
              },
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "12",
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: true,
            },
            data: currentData.labels.map((label, index) => ({
              name: label,
              value: currentData.energyData[index],
              itemStyle: {
                color: currentData.colors[index],
              },
            })),
          },
        ],
      };

      // 电费图表配置
      const billOption = {
        title: {
          text: this.getTimeDimensionTitle() + " - 电费",
          left: "center",
          textStyle: {
            color: "#64748b",
            fontSize: 14,
            fontWeight: "bold",
          },
          top: 20,
        },
        tooltip: {
          trigger: "item",
          formatter: (params) => {
            const percentage = ((params.value / billTotal) * 100).toFixed(1);
            return `${params.name}<br/>${params.marker} ${params.value} 元 (${percentage}%)`;
          },
        },
        legend: {
          show: true,
          bottom: 0,
          left: "center",
          textStyle: {
            color: "#64748b",
          },
        },
        series: [
          {
            name: "分组电费",
            type: "pie",
            radius: ["40%", "70%"],
            center: ["50%", "55%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 5,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: {
              show: true,
              formatter: (params) => {
                const percentage = ((params.value / billTotal) * 100).toFixed(1);
                return `{name|${params.name}}\n{value|${params.value} 元}\n{percentage|${percentage}%}`;
              },
              rich: {
                name: {
                  fontSize: 10,
                  color: "#64748b",
                },
                value: {
                  fontSize: 12,
                  fontWeight: "bold",
                  color: "#333",
                  lineHeight: 18,
                },
                percentage: {
                  fontSize: 10,
                  color: "#999",
                },
              },
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "12",
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: true,
            },
            data: currentData.labels.map((label, index) => ({
              name: label,
              value: currentData.billData[index],
              itemStyle: {
                color: currentData.colors[index],
              },
            })),
          },
        ],
      };

      this.groupChartEnergy.setOption(energyOption);
      this.groupChartBill.setOption(billOption);
      window.addEventListener("resize", this.handleResize);
    },

    getTimeDimensionTitle() {
      const titles = {
        day: "日维度",
        month: "月维度",
        year: "年维度",
      };
      return titles[this.currentTimeDimension];
    },

    handleResize() {
      if (this.groupChartEnergy) {
        this.groupChartEnergy.resize();
      }
      if (this.groupChartBill) {
        this.groupChartBill.resize();
      }
    },
    downloadChart() {
      if (!this.groupChartEnergy || !this.groupChartBill) {
        console.error("图表实例不存在");
        return;
      }

      try {
        // 获取两个图表的图片数据
        const energyDataURL = this.groupChartEnergy.getDataURL({
          type: "png",
          pixelRatio: 2,
          backgroundColor: "#fff",
        });

        const billDataURL = this.groupChartBill.getDataURL({
          type: "png",
          pixelRatio: 2,
          backgroundColor: "#fff",
        });

        // 创建一个合并图片的函数
        this.mergeImagesAndDownload(energyDataURL, billDataURL);
      } catch (error) {
        console.error("获取图表数据失败:", error);
      }
    },

    // 合并两张图片并下载
    mergeImagesAndDownload(img1Src, img2Src) {
      // 创建两个图片对象
      const img1 = new Image();
      const img2 = new Image();

      // 加载第一张图片
      img1.onload = () => {
        // 加载第二张图片
        img2.onload = () => {
          // 创建 canvas
          const canvas = document.createElement("canvas");
          const ctx = canvas.getContext("2d");

          // 设置边距和标题高度
          const margin = 20;
          const titleHeight = 40;
          const chartHeight = Math.max(img1.height, img2.height);

          // 正确计算 canvas 尺寸
          canvas.width = img1.width + img2.width + margin * 3;
          canvas.height = chartHeight + margin * 2 + titleHeight;

          // 绘制白色背景
          ctx.fillStyle = "#fff";
          ctx.fillRect(0, 0, canvas.width, canvas.height);

          // 绘制标题
          ctx.font = "bold 24px Arial";
          ctx.fillStyle = "#64748b";
          ctx.textAlign = "center";
          ctx.fillText("分组能耗统计", canvas.width / 2, margin + titleHeight / 2 + 8);

          // 绘制两张图表图片，带边距
          const chartY = margin + titleHeight;
          ctx.drawImage(img1, margin, chartY);
          ctx.drawImage(img2, img1.width + margin * 2, chartY);

          // 转换为数据URL并下载
          const mergedDataURL = canvas.toDataURL("image/png");
          const link = document.createElement("a");
          link.download = `分组能耗统计图表_${new Date().getTime()}.png`;
          link.href = mergedDataURL;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        };

        img2.src = img2Src;
      };

      img1.src = img1Src;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./EnergyAnalysis.scss";

.chart-container {
  display: flex;
}

.chart-wrapper {
  width: 45%;
  height: 420px;
}

.trend-up {
  color: #10b981;
  font-weight: 500;
  font-size: 0.85rem;
  text-align: center;

  i {
    margin-right: 3px;
  }
}

.trend-down {
  color: #ef4444;
  font-weight: 500;
  font-size: 0.85rem;
  text-align: center;

  i {
    margin-right: 3px;
  }
}

.table-view {
  border-radius: 12px;
  border: 1px solid rgba(0, 102, 255, 0.1);
  overflow: hidden;
  margin-top: 20px;
}

.main-analysis {
  margin-top: 20px;
  border-radius: 12px;
  border: 1px solid rgba(0, 102, 255, 0.1);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.main-analysis-header {
  display: flex;
  align-items: center;
  font-size: 1.2rem;
  font-weight: 600;
  color: #0066ff;
  margin-bottom: 20px;

  .svg-icon {
    margin-right: 10px;
    font-size: 1.3rem;
    width: 1.3rem;
    height: 1.3rem;
  }
}

.main-analysis-content {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.main-analysis-content-item {
  background: #f8fafc;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;

  div:first-child {
    font-size: 0.9rem;
    color: #64748b;
    margin-bottom: 8px;
  }

  .main-analysis-content-item-value {
    font-size: 1.1rem;
    font-weight: 600;
    color: #0066ff;
  }
}

@media (max-width: 768px) {
  .chart-card {
    flex-direction: column;

    .stat-card {
      width: 100%;
      margin-bottom: 15px;
    }
  }

  .main-analysis-content {
    grid-template-columns: 1fr;
  }

  .chart-container {
    flex-direction: column;
  }

  .chart-wrapper {
    width: 100%;
    height: 300px;
    margin-bottom: 20px;
  }
}
</style>
